/**
 * 格式化时间
 */
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * 格式化数字，保证两位数显示
 */
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 检查登录状态
 */
function checkLoginStatus() {
  return new Promise((resolve, reject) => {
    const isAuthenticated = wx.getStorageSync('isAuthenticated') || false
    if (isAuthenticated) {
      resolve(true)
    } else {
      // 如果未登录，跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login'
      })
      resolve(false)
    }
  })
}

/**
 * 显示消息提示
 */
function showToast(message, type = 'none') {
  wx.showToast({
    title: message,
    icon: type, // 可选值：success, error, loading, none
    duration: 2000
  })
}

/**
 * 显示加载中提示
 */
function showLoading(message = '加载中...') {
  wx.showLoading({
    title: message,
    mask: true
  })
}

/**
 * 隐藏加载提示
 */
function hideLoading() {
  wx.hideLoading()
}

/**
 * 网络请求封装
 */
function request(options) {
  return new Promise((resolve, reject) => {
    // 显示加载
    showLoading()
    
    // 请求默认配置
    const defaultOptions = {
      header: {
        'content-type': 'application/json'
      }
    }
    
    // 合并选项
    const requestOptions = {
      ...defaultOptions,
      ...options,
      success: (res) => {
        hideLoading()
        resolve(res.data)
      },
      fail: (err) => {
        hideLoading()
        showToast('网络请求失败', 'error')
        reject(err)
      }
    }
    
    // 发起请求
    wx.request(requestOptions)
  })
}

/**
 * 格式化日期（年-月-日）
 */
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

module.exports = {
  formatTime,
  formatNumber,
  checkLoginStatus,
  showToast,
  showLoading,
  hideLoading,
  request,
  formatDate
} 